package com.ddd.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    private static final Long JWT_TTL = 60* 60*1000l;

    public static final String JWT_KEY = "ddd";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replace("-", "");
        return  token;
    }


    public static  String createJWT(String subject){
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
        return builder.compact();
    }

    public static  String createJWT(String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
        return builder.compact();
    }


    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis , String uuid){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey =  generalKey();
        long nowMills = System.currentTimeMillis();

        Date now = new Date(nowMills);

        if (ttlMillis == null){
            ttlMillis = JWT_TTL;
        }

        long expMillis = nowMills + ttlMillis;

        Date expDate = new Date(expMillis);

        return Jwts.builder()
                .setId(uuid) // 唯一ID
                .setSubject(subject)   // 主题
                .setIssuer("sg") // 签发者
                .setIssuedAt(now) // 签发时间
                .signWith(signatureAlgorithm, secretKey) // 使用HS256对称加密算法签名
                .setExpiration(expDate);
    }

    public  static String createJWT(String id, String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return builder.compact();
    }

    public static SecretKey generalKey(){
        byte[] decode = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKeySpec aes = new SecretKeySpec(decode, 0, decode.length, "AES");
        return aes;
    }

    public static Claims parseJWT(String jwt){

        SecretKey secretKey = generalKey();

        return Jwts.parser().setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }


    public static void main(String[] args) {
        String jwt = createJWT("ddd");
        System.out.println(jwt);
        Claims claims = parseJWT(jwt);
        System.out.println(claims);
        System.out.println(claims.getSubject());
    }
}
